using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GravityResolver : FieldEngine.MonoResolver
{
  [SerializeField]
  private IGridBallReloader.Mono _ballReloader;

  private Dirty m_dataDrity;
  public override void Resolve(IResolveEngine<FieldModel>.ResolveContext context) {
    var grid = context.Model.gridModel;
    var size = grid.size;
    int[] holeCountPerColumn = new int[size.x];
    for (int x = 0; x < size.x; x++)
    {
      for (int y = 0; y < size.y; y++)
      {
        var ball = grid.GetBallModel(x, y);
        if (!ball.isEmpty)
        {
          continue;
        }

        var hole = new Vector2Int(x, y);
        var holeCount = 1;
        for (int availY = y + 1; availY < size.y; availY++)
        {
          var availBall = grid.GetBallModel(x, availY);
          if (availBall.isEmpty)
          {
            holeCount++;
            continue;
          }
          m_dataDrity.Set();
          grid.SwapBall(hole, new Vector2Int(x, availY));
          hole.y++;
        }
        if (holeCount > 0)
        {
          m_dataDrity.Set();
        }
        holeCountPerColumn[x] = holeCount;
        break;
      }
    }

    if (m_dataDrity.Pop())
    {
      if (_ballReloader != null)
      {
        var reloadRequset = new IGridBallReloader.Request() {
          fieldModel = context.Model,
          lackOfBall = holeCountPerColumn
        };

        _ballReloader.HandleRequest(reloadRequset);
      }

      context.pushRegisteredHolder(FieldView.HOLDER_KEY);
    }
  }



}
